import urllib
import utility
import re
import xbmcgui
import xbmc

class SVTConfig(object):
    BaseUrl = "http://svtplay.se"		
    NextPage = "N&#228;sta sida"
    
class SVTFactory(utility.ParserFactory):
    
    def _getDefaultParser(self):
        return StartPageParser()

#Content parsers

class SVTParser(utility.WebParser):
    
    def onAddItemURL(self, url):
        return self.fixUrl(url)   
    
    def fixUrl(self, url):
            
        if url[0:4].lower() == "rtmp":                        
            return url.replace("_definst_","?slist=")
            
        if url[0:4].lower() == "http":
            return url
            
        if url[0] == "/":
            return SVTConfig.BaseUrl + url            
        
        if url[0] == "?":                  
            if self.URL.find("?") > 0:
                return self.URL.split("?")[0] + url
           
            return self.URL + '/' + url
               
        return url

class StartPageParser( SVTParser ):
    
    def getDefaultURL(self):
        return SVTConfig.BaseUrl
    
    def onParse(self, url, data):
        self._addFolderItem(SVTConfig.BaseUrl + "/alfabetisk", "Program A-&#214;", ProgramsAOParser)
        self._addFolderItem(SVTConfig.BaseUrl + "/kategorier", "Kategorier", CategoryParser)        
        
        subselection = re.compile('<div\\sid="pb"[^>].*?>[\W\w]+?</div>').findall(data, re.DOTALL)
        
        if not subselection: raise utility.ParserError(url)
               
        categories = re.compile('<a\\shref="(?P<curl>[^"]*?)"\\sclass="[^i]*?internal[^"]*?"[^>]*?>(?P<title>[^<]*?)</a>').findall(subselection[0], re.DOTALL)            

        for curl, title in categories:
            #Exclude live category
            if title.lower().find("lives") == 0:
                continue
            
            self._addFolderItem(curl, title, EpisodeParser)
            
class ProgramsAOParser( SVTParser ):
    
    def onParse(self, url, data):    
        programs = re.compile('<li>\W+<a href="([^"]+)">([^<]+)</a>\W+</li>').findall(data, re.DOTALL)
    
        for purl, title in programs:
            self._addFolderItem(purl, title, ProgramPartsParser)
            
class CategoryParser( SVTParser ):
    
    def onParse(self, url, data):
        ul = re.compile('<ul class="list category-list[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)
        
        if not ul: raise utility.ParserError(url)
        
        categories = re.compile('<li class="[^"]*">\W+<div class="container">\W*<a href="([^"]+)"[^>]*>\W*<img[^>]+src="([^"]+)[^>]+>\W*<span class="bottom"></span>\W*<span class="[^"]*">([^>]+)</span>').findall(ul[0], re.DOTALL)
    
        for curl, image, title in categories:            
            self._addFolderItem(curl, title, CategoryProgramsParser, image)      

class CategoryProgramsParser( SVTParser ):
    
    def onParse(self, url, data):
    
        uls = re.compile('<ul class="list[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)
        
        for ul in uls:        
            programs = re.compile('<li class="[^"]*">\W*<a href="([^"]+)"[^>]*>\W*<img[^>]+src="([^"]+)[^>]+>\W*(<!--[^/]+/span -->\W+){0,1}<span>([^>]+)</span>').findall(ul, re.DOTALL)
    
            for purl, image, co, title in programs:
                self._addFolderItem(purl, title.strip(), ProgramPartsParser, image)
            
                
                
class ProgramPartsParser( SVTParser ):
    
    def onParse(self, url, data):
    
        ul = re.compile('<ul class="navigation playerbrowser">[\W\w]+?</ul>').findall(data, re.DOTALL)
        
        if not ul: raise utility.ParserError(url)
        
        parts = re.compile('<li class="[^"]*">\W+(<h2>)*\W*<a href="([^"]+)"[^>]+>([^<]+)</a>').findall(ul[0], re.DOTALL)
        
        if len(parts) == 1:            
            self._extend( EpisodeParser().parse(url+urllib.unquote_plus(parts[0][1])))
        else:
            for h2, purl, title in parts:                                    
                self._addFolderItem(purl, title, EpisodeParser)

class EpisodeParser( SVTParser ):
    
    def onParse(self, url, data):
        
        ul = None
        
        if url.find( SVTConfig.BaseUrl + "/?" ) != -1:
            #special start-page match
            ul = re.compile('<ul class="list\s[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)
        else:       
            ul = re.compile('<ul class="list small[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)
        
        if not ul: raise utility.ParserError(url)
        
        episodes = re.compile('<li class="[^"]*"\W*>\W+<a href="([^"]+)"[^>]+title="([^"]*)"[^>]+>\W+<img[^>]+src="([^"]+)[^>]+>\W+(<!--[^/]+/span -->\W+){0,1}<span[^>]*>([^<]+)</span>').findall(ul[0], re.DOTALL)
        for purl, info, image, comment, title in episodes:            
            self._addImageItem(purl, title.strip(), VideoParser, image)
            
        pagenum = re.compile('<ul class="list small[^"]*pagenum:(\d+)[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)
        
        if not pagenum: raise utility.ParserError(url, "Unable to find number of pages to parse.")
            
        pagecount = int(pagenum[0])    
        it = url[url.rindex('/') + 1:len(url)].split(',')
        current = int(it[2])
    
        if (current < pagecount):
            it[2] = str(current + 1)
            self._addFolderItem( url[0:url.rindex('/') + 1] + ','.join(it), SVTConfig.NextPage, EpisodeParser)
    
class VideoParser( SVTParser ):

    def onParse(self, url, data):

        match = re.compile('dynamicStreams=url:([^,]+)').findall(data, re.DOTALL)

        videoUrl = ""

        if match:
            videoUrl = match[0]
            if len( videoUrl ) > 5 and videoUrl[0:5] == "rtmpe":
                match = re.compile('<param name="movie" value="([^"]+)').findall(data, re.DOTALL)
                if match:
                    videoUrl = videoUrl + " swfvfy=true swfurl=" + SVTConfig.BaseUrl + match[0]

        else:
            match = re.compile('pathflv=([^&]+)').findall(data, re.DOTALL)
            if match: 
                videoUrl = match[0]
                if len( videoUrl ) > 5 and videoUrl[0:5] == "rtmpe":
                    match = re.compile('<param name="movie" value="([^"]+)').findall(data, re.DOTALL)
                    if match:
                        videoUrl = videoUrl + " swfvfy=true swfurl=" + SVTConfig.BaseUrl + match[0]


        if len(videoUrl) == 0: raise utility.ParserError(url)
			
        self._addVideoItem(videoUrl, "Video")
        

utility.ContentFactory = SVTFactory()